package tt.dz.order.schedulingjob;

import java.util.ArrayList;
import java.util.List;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.ContextLoader;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import tt.dz.order.pojo.OrderAccountingStatus;
import tt.dz.order.pojo.OrderInfo;
import tt.dz.order.pojo.OrderItemDividedDetail;
import tt.dz.order.service.rpc.client.MsRpcClient;
import tt.dz.order.util.OrderConstant.DividedFlag;
import tt.dz.order.util.OrderConstant.OrderPayStatus;
import tt.dz.order.util.OrderConstant.OrderPayWay;
import tt.dz.order.util.OrderConstant.OrderType;
import tt.dz.order.vo.AccountingInfo;
import tt.dz.order.vo.AccountingInfo.SubItem;

/**
 * @Title 向主服务器发送台帐信息的job
 * @author zhoutian   
 * @date 2015-11-17
 */
@Component
public class SendAccountingInfoJob extends QuartzJobBean {
	private static Logger log = LoggerFactory.getLogger(SendAccountingInfoJob.class);
	
	//截取的大小
	private int subSize = 50;
	
	//失败次数
	private int failCount = 3;
	
	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=java.lang.Exception.class)
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		log.info("发送台帐信息job start");
		List<OrderAccountingStatus> list = null;
			//获取需要发送台帐信息的订单列表
			list = OrderAccountingStatus.getAccountingInfoForSend(failCount);
		if(list != null && !list.isEmpty()){
			//截取一部分（50个）订单发送台帐信息
			List<OrderAccountingStatus> subList ;
			List<String> orderNos ;
			if(list.size() >= subSize){
				subList = list.subList(0, subSize);
				orderNos = new ArrayList<String>(subSize);
			} else {
				subList = list;
				orderNos = new ArrayList<String>(list.size());
			}
			for(OrderAccountingStatus orderAccountingStatus : subList){
				orderNos.add(orderAccountingStatus.getOrderNo());
			}
			//组装台帐信息
			List<AccountingInfo> accountingInfoList = assembleAccountingInfo(orderNos);
			//修改订单台帐信息状态为"正在发送"
			OrderAccountingStatus.changeStatusToSending(orderNos);
			//发送台帐信息
			try {
				MsRpcClient msRpcClient = (MsRpcClient) ContextLoader.getCurrentWebApplicationContext().getBean("msRpcClient");
				String result = msRpcClient.trade(accountingInfoList);
				if(result != null){
					JSONObject resultJSON = JSON.parseObject(result);
					String isSuccess = resultJSON.getString("isSuccess");
					if(isSuccess != null && "1".equals(isSuccess)){
						//如果主服务器返回成功，修改订单台帐信息状态为"发送成功"
						OrderAccountingStatus.changeStatusToSuccess(orderNos);
					} else {
						//返回失败，则修改订单台帐信息状态为"需要再次发送"
						OrderAccountingStatus.changeStatusToNeedSendAgain(orderNos);
					}
				} else {
					//返回失败，则修改订单台帐信息状态为"需要再次发送"
					OrderAccountingStatus.changeStatusToNeedSendAgain(orderNos);
					if(subList != null && !subList.isEmpty()){
						for(OrderAccountingStatus  orderAccountingStatu : subList){
							log.error("orderNo为" + orderAccountingStatu.getOrderNo() + "的订单发送失败" + (orderAccountingStatu.getFailCount()+1) + "次");
						}
					}
				}
			} catch(Exception e){
				log.error("", e);
				OrderAccountingStatus.changeStatusToNeedSendAgain(orderNos);
			}
		}
	}
	/**
	 * 组装台账信息
	 * @param orderNos
	 * @return
	 */
	private List<AccountingInfo> assembleAccountingInfo(List<String> orderNos) {
		List<OrderInfo> orderList = OrderInfo.getByIds(orderNos);
		List<AccountingInfo> accountingInfoList = new ArrayList<AccountingInfo>(orderList.size());
		Integer orderType = OrderType.AFTER_PAYMENT.value();
		for(OrderInfo order : orderList){
			AccountingInfo aInfo = new AccountingInfo();
			aInfo.setOrderNo(order.getOrderNo());
			if(order.getOrderType()!=null){
				orderType = order.getOrderType();
			}
			aInfo.setOrderType(orderType);
			aInfo.setRelatedOrderNo(order.getRelatedOrderNo());
			aInfo.setServiceNo(order.getServiceNo());
			aInfo.setCardNo(order.getCardNo());
			aInfo.setCardType(order.getCardType());
			aInfo.setPayerBalance(order.getPayerBalance());
			aInfo.setOriginalPayer(order.getUserId());
			aInfo.setPayer(order.getRealPayer());
			aInfo.setRealReceiver(order.getRealReceiver());
			aInfo.setPaymentAmount(order.getCaculatedTotalPrice());
			aInfo.setPayTypeCode(order.getPayTypeCode());
			if(aInfo.getPayTypeCode() == OrderPayWay.unify.value() || aInfo.getPayTypeCode() == OrderPayWay.enterprise.value()){
				//如果是统付或企业客户支付，则支付状态为"未支付"
				aInfo.setPayStateCode(OrderPayStatus.unpay.value());
			} else {
				aInfo.setPayStateCode(OrderPayStatus.payed.value());
			}
			aInfo.setChannelCode(order.getPayChannelCode());
			aInfo.setAppId(order.getAppId());
			if(aInfo.getPayTypeCode() == OrderPayWay.thirdImmediately.value()){
				aInfo.setThdPaySeq(order.getThdPaySeq());
				aInfo.setThdPayAmount(order.getThdPayAmount());
				aInfo.setThdPoundage(order.getThdPoundage());
				aInfo.setThdEndTime(order.getThdEndTime());
				aInfo.setResponseCode(order.getTradeStatusCode());
				//aInfo.setTranTime(tranTime);
			}
			//用OrderItemDividedDetail构造发送的台帐信息里的SubItem
			List<OrderItemDividedDetail> orderItemDetailList = OrderItemDividedDetail.getByOrderNo(order.getOrderNo());
			List<SubItem> subItemList = null  ;
			if(orderItemDetailList != null && !orderItemDetailList.isEmpty()){
				subItemList = new ArrayList<SubItem>(orderItemDetailList.size());
				for(OrderItemDividedDetail orderItemDetail : orderItemDetailList){
					SubItem subItem = new SubItem();
					subItem.setServiceNo(orderItemDetail.getServiceNo());
					subItem.setServiceProvider(orderItemDetail.getServiceProvider());
					subItem.setIsCost(orderItemDetail.getIsCost());
					subItem.setReceiver(orderItemDetail.getReceiver());
					subItem.setPaymentAmount(orderItemDetail.getSplitedPrice());
					if(orderItemDetail.getTotalPrice().equals(orderItemDetail.getSplitedPrice())){
						subItem.setIsDivided(DividedFlag.no.value());
					} else {
						subItem.setIsDivided(DividedFlag.yes.value());
					}
					subItemList.add(subItem);
				}
			}
			aInfo.setTranSubVOList(subItemList);
			accountingInfoList.add(aInfo);
		}
		return accountingInfoList;
	}
}
